package com.ykdl.app.Utils;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import com.photoselector.model.ImageBean;
import com.photoselector.ui.PhotoSelectorActivity;

import com.ykdl.app.connect.Constants;
import com.ykdl.app.prefs.MyPrefs;

/**
 * 图片压缩类
 * 
 * @author jiafeiyu
 * 
 */
public class CameraUtils {
	public static final int SURVEY_CAMERA_WITH_DATA = 23; // 照相机
	public static final int SURVEY_PHOTO_WITH_DATA = 24; // 相册
	public static final int SURVEY_PHOTO_ZOOM = 25; // 缩放
	public static final int SURVEY_PHOTO_CROP = 26;
	private String localCameraPath = "";// 拍照后得到的图片地址
	public static final String IMAGE_UNSPECIFIED = "image/*";
	private Activity mCurrentAcitiy;

	public CameraUtils(Activity activity) {
		this.mCurrentAcitiy = activity;
	}
	private ArrayList<ImageBean> mChecked;
	private boolean isSingle;

	
	


	public void setSingle(boolean isSingle) {
		this.isSingle = isSingle;
	}

	public void setSelected(ArrayList<ImageBean> selected) {
		this.mChecked = selected;
		if (mChecked==null) {
			mChecked = new ArrayList<ImageBean>();
		}
	}

	// 跳转到拍照
	public void startCamera(String path,boolean isSingle) {
		this.isSingle = isSingle;
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		String fileUri = Environment.getExternalStorageDirectory().toString() + path;
		File dir = new File(fileUri);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File(dir, String.valueOf(System.currentTimeMillis())
				+ ".jpg");
		localCameraPath = file.getPath();
		Uri imageUri = Uri.fromFile(file);
		MyPrefs.setCamePath(mCurrentAcitiy.getBaseContext(), imageUri.getPath());
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		mCurrentAcitiy.startActivityForResult(openCameraIntent,
				SURVEY_CAMERA_WITH_DATA);

		/*
		 * try { String fileUri =
		 * Environment.getExternalStorageDirectory().toString() + path; File out
		 * = new File(fileUri); if (!out.exists()) { out.mkdirs(); } String
		 * fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
		 * + ".jpg";// 照片命名 out = new File(fileUri, fileName); fileUri = fileUri
		 * + fileName;// 该照片的绝对路径 Uri cametaImageUri = Uri.fromFile(out);
		 * MyPrefs.setCamePath(mCurrentAcitiy.getBaseContext(),
		 * cametaImageUri.toString()); //
		 * MyPrefs.setSmallCamePath(mCurrentAcitiy.getBaseContext(),
		 * smallpicPath); path = Uri.fromFile(out).toString(); Intent intent =
		 * new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		 * intent.putExtra(MediaStore.EXTRA_OUTPUT, cametaImageUri);
		 * intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,
		 * SURVEY_CAMERA_WITH_DATA);
		 * mCurrentAcitiy.startActivityForResult(intent,
		 * SURVEY_CAMERA_WITH_DATA); } catch (Exception e) {
		 * Toast.makeText(mCurrentAcitiy,"", Toast.LENGTH_SHORT).show(); }
		 * return path;
		 */
	}

	public String compressImage(String path) {
		Bitmap mBitmap = BitmapManager.getSmallBitmap(path);
		// mBitmap = BitmapFactory.decodeFile(imageUrl);
		BitmapManager.saveBitmap(path.replace(".jpg", "s.jpg"), mBitmap);
		return path.substring(0, path.indexOf(".jpg")) + "s.jpg";
	}

	public ArrayList<ImageBean> onActivityResult(int requestCode,
			int resultCode, Intent data) {
		ArrayList<ImageBean> selected = new ArrayList<ImageBean>();
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == SURVEY_CAMERA_WITH_DATA) {
				if (data!=null) {
					
					Uri selectedImage = data.getData();
					String localSelectPath = "";
					if (selectedImage != null) {
						Cursor cursor = mCurrentAcitiy.getContentResolver().query(
								selectedImage, null, null, null, null);
						cursor.moveToFirst();
						int columnIndex = cursor.getColumnIndex("_data");
						localCameraPath = cursor.getString(columnIndex);
						cursor.close();
						ImageBean info = new ImageBean();
						info.setOriginalPath(localCameraPath);
						if (isSingle) {
							
							selected.add(info);
						}else {
							if (mChecked!=null) {
								mChecked.add(info);
							}
						}
					}
				}else {
					String	mImageUrl = MyPrefs.getCamePath(mCurrentAcitiy);
					ImageBean info = new ImageBean();
					info.setOriginalPath(mImageUrl);
					
					if (isSingle) {
						
						selected.add(info);
					}else {
						if (mChecked!=null) {
							mChecked.add(info);
						}
					}
				}
			} else if (requestCode == SURVEY_PHOTO_WITH_DATA) {
				
				List<ImageBean> mPhotoList = (ArrayList<ImageBean>) data
						.getSerializableExtra("photos");
				selected.addAll(mPhotoList);
			} else if (requestCode == SURVEY_PHOTO_ZOOM) {
	
			}
		}
		/*
		 * String mImageUrl; ArrayList<ImageBean> selected = new
		 * ArrayList<ImageBean>(); if (data!=null) { if (requestCode ==
		 * SURVEY_CAMERA_WITH_DATA ) {
		 * 
		 * mImageUrl = MyPrefs.getCamePath(mCurrentAcitiy); ImageBean info = new
		 * ImageBean(); info.setOriginalPath(mImageUrl); selected.add(info);
		 * }else if(requestCode == SURVEY_PHOTO_WITH_DATA) { List<ImageBean>
		 * mPhotoList = (ArrayList<ImageBean>)
		 * data.getSerializableExtra("photos"); selected.addAll(mPhotoList);
		 * }else if(requestCode == SURVEY_PHOTO_ZOOM){
		 * 
		 * } }
		 */
		if (requestCode == SURVEY_CAMERA_WITH_DATA&&!isSingle) {
			return mChecked;
		}
		return selected;
	}

	public String getPath(String localCameraPath) {

		String dirFile = Environment.getExternalStorageDirectory().toString()
				+ Constants.COMPRESS_PATH;
		File dirfile = new File(dirFile);
		if (!dirfile.exists()) {
			dirfile.mkdirs();
		}
		File originalFile = new File(dirFile, System.currentTimeMillis()
				+ ".jpg");
		FileOutputStream fileOutputStream = null;
		try {
			fileOutputStream = new FileOutputStream(originalFile);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Bitmap bit = getImage(localCameraPath);

		// bit.compress(Bitmap.CompressFormat.JPEG, 100,
		// fileOutputStream);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		// int options = 100;
		bit.compress(CompressFormat.JPEG, 80, fileOutputStream);
		return originalFile.getAbsolutePath();
	}

	private Bitmap getImage(String srcPath) {
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空

		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 800f;// 这里设置高度为800f
		float ww = 480f;// 这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
		return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
	}

	private Bitmap compressImage(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;// 每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		return bitmap;
	}

	public void startPhotos(int mMaxSize, ArrayList<ImageBean> selected) {
		Intent intent = new Intent(mCurrentAcitiy, PhotoSelectorActivity.class);
		intent.putExtra("key_max", mMaxSize);
		intent.putExtra("mCheckedList", selected);
		mCurrentAcitiy.startActivityForResult(intent, SURVEY_PHOTO_WITH_DATA);
	}
	

	/**
	 * FIXME Comment this method desc：startPhotoZoom图片剪切的方法
	 * 
	 * @param uri
	 *            图片的URI地址
	 */

	public void startPhotoZoom(Uri uri,int aspectX,int aspectY) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", aspectX);
		intent.putExtra("aspectY", aspectY);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("scale", true);//黑边
        intent.putExtra("scaleUpIfNeeded", true);//黑边
        if (aspectX==1) {
			
        	intent.putExtra("outputX", 300);
		}else {
			intent.putExtra("outputX", 400);
		}
		intent.putExtra("outputY", 300);
		intent.putExtra("return-data", true);
		mCurrentAcitiy.startActivityForResult(intent, SURVEY_PHOTO_ZOOM);
	}
	
	/**
	 * FIXME Comment this method desc：saveFile创建图片文件
	 * 
	 * @param bm
	 *            图片
	 * @param fileName
	 *            图片名字
	 * @throws IOException
	 *             抛出IO异常
	 */
	public String saveFile(Bitmap bm, String path) throws IOException {
		String imagePath =getSystemPath()+ path  + String.valueOf(System.currentTimeMillis()+".png");
		String dirpath = getSystemPath()+ path;
		File dirFile = new File(dirpath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		File file = new File(imagePath);
		file.createNewFile();
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(file));
		bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
		bos.flush();
		bos.close();
		return imagePath;
		
	}
	
	private String getSystemPath(){
		return Environment.getExternalStorageDirectory().toString();
	}
}
